import {Fragment, PureComponent} from 'react';
import {
  Card,
  Popconfirm,
  Form,
  Row,
  Col,
  Input,
  Button,
  message,
  DatePicker,
  Modal,
  Tooltip
} from 'antd';
import {
  EyeOutlined
} from '@ant-design/icons';
import React from 'react';
import Icon from '@ant-design/icons';
import {connect} from "umi";
import {formatMessage} from "@@/plugin-locale/localeExports";
import ProTable from '@ant-design/pro-table';
import styles from '../common.less';
import {hasPermission, nopermission} from "@/hasPermission";
import ReactJson from 'react-json-view';
const { RangePicker } = DatePicker;


class SysLogs extends PureComponent{

  state = {
    formValues: {},
    updateFormValues: {},
    currentPage: 1,
    pageSize: 10,
    stime: null,
    etime: null,
    jsonViewVisible: false,
    jsonStr: null
  }

  columns = [
    {
      title: formatMessage({ id: 'app.sysLogs.loginName' }),
      dataIndex: 'loginName',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.largeModel' }),
      dataIndex: 'largeModel',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.smallModel' }),
      dataIndex: 'smallModel',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.remark' }),
      dataIndex: 'remark',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.actionType' }),
      dataIndex: 'actionType',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.requestUrl' }),
      dataIndex: 'requestUrl',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.params' }),
      dataIndex: 'params',
      align: 'center',
      render: text => text && text != '-' &&
        <Tooltip title="点击查看">
          <a onClick={() => this.handleJsonView(true, text)}><EyeOutlined size={20} /></a>
        </Tooltip>
    },
    {
      title: formatMessage({ id: 'app.sysLogs.ip' }),
      dataIndex: 'ip',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.sysLogs.actionDate' }),
      dataIndex: 'actionDate',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: '100px',
      render: (text, record) => (
        <Fragment>
          <Popconfirm
          title={formatMessage({ id: 'app.common.confirm-delete' })}
          onConfirm={() => this.deleteRecord(record.id)}
          >
            <a>
              <Icon type='delete' />
              {formatMessage({ id: 'app.common.delete' })}
            </a>
          </Popconfirm>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysLogs/fetch'
    })
    this.formRef = React.createRef();
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    };
    if (sorter.field && sorter.order) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({ currentPage: pagination.current, pageSize: pagination.pageSize });
    dispatch({
      type: 'sysLogs/fetch',
      payload: params
    });
  };

  handleSearch = e => {
    const { dispatch } = this.props;
    const { stime, etime } = this.state;
    const values = {
      ...e
    };
    this.setState({
      formValues: values
    });
    if (e == null) {
      values.currentPage = this.state.currentPage;
      values.pageSize = this.state.pageSize;
    } else {
      values.currentPage = 1;
      values.pageSize = 10;
    }
    values.rangeTime = undefined;
    values.stime = stime;
    values.etime = etime;
    dispatch({
      type: 'sysLogs/fetch',
      payload: values
    });
  };

  handleFormReset = () => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    this.setState({
      formValues: {},
      currentPage: 1,
      pageSize: 10,
      stime: null,
      etime: null
    });
    dispatch({
      type: 'sysLogs/fetch'
    });
  };

  deleteRecord = id => {
    if (!hasPermission('admin:delete')){
      nopermission();
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'sysLogs/deleteById',
      payload: {
        id: id
      }
    }).then(res => {
      if (res.status == 200){
        message.success('删除成功！');
        this.handleSearch();
      }
    })
  };

  handleRangeChg = (date, dateString) => {
    this.setState({
      stime: dateString[0] + " 00:00:00",
      etime: dateString[1] + " 23:59:59"
    })
  };

  handleJsonView = (flag, str) => {
    this.setState({
      jsonViewVisible: !!flag,
      jsonStr: str || null
    })
  }

  renderSimpleForm() {

    return (
      <Form ref={this.formRef} onFinish={this.handleSearch}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.sysLogs.loginName' })} name='loginName'>
              <Input placeholder={formatMessage({ id: 'app.sysLogs.loginName' })} />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.sysLogs.largeModel' })} name='largeModel'>
              <Input placeholder={formatMessage({ id: 'app.sysLogs.largeModel' })} />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.sysLogs.smallModel' })} name='smallModel'>
              <Input placeholder={formatMessage({ id: 'app.sysLogs.smallModel' })} />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.sysLogs.actionType' })} name='actionType'>
              <Input style={{width: '90%'}} placeholder={formatMessage({ id: 'app.sysLogs.actionType' })} />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.sysLogs.requestUrl' })} name='requestUrl'>
              <Input style={{width: '90%'}} placeholder={formatMessage({ id: 'app.sysLogs.requestUrl' })} />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.sysLogs.actionDate' })} name='rangeTime'>
              <RangePicker onChange={this.handleRangeChg} />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>
                <Icon type='search'/>{formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type='primary'
              >
                <Icon type='reload'/>{formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  };

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      sysLogs: {data},
      loading
    } = this.props;
    const { jsonViewVisible, jsonStr } = this.state;

    return (
      <>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <ProTable
            bordered={true}
            search={false}
            rowKey={record => record.id}
            loading={loading}
            dataSource={data ? data.list : []}
            pagination={data ? data.pagination : {}}
            columns={this.columns}
            onChange={this.handleBasicTableChange}
            options={{
              density: true,
              reload: () => {
                this.handleSearch();
              },
              fullScreen: true,
              setting: true
            }}
          />
        </div>
      </Card>
        {jsonViewVisible && jsonStr &&
          <Modal
            title={formatMessage({ id: 'app.sysLogs.params' })}
            visible={jsonViewVisible}
            onCancel={() => this.handleJsonView(false)}
            footer={null}
          >
            <ReactJson iconStyle='square' theme='google' displayDataTypes={false} src={JSON.parse(jsonStr)} />
          </Modal>
        }
      </>
    )
  }
}

export default connect(({ sysLogs, loading }) => ({
  sysLogs,
  loading: loading.effects['sysLogs/fetch']
}))(SysLogs);
